package com.iboxpay.open.auth.center.redis.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iboxpay.open.auth.center.config.JedisConfig;

import io.codis.jodis.JedisResourcePool;
import io.codis.jodis.RoundRobinJedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 
 * JedisPoolFactory.java
 * @author xuxiao
 * @date 2018/06/25
 */
@Service
public class JedisPoolFactory {
	
	protected static final Logger LOGGER = LoggerFactory.getLogger(JedisPoolFactory.class);
	
	@Autowired
    private JedisConfig jedisConfig;
	
	public JedisResourcePool createJedisPool() {
		return createCodisPool();
	}

    public JedisResourcePool createCodisPool(){
    	RoundRobinJedisPool jedisPool = null;
    	try {
			jedisPool = RoundRobinJedisPool.create()
					.curatorClient(jedisConfig.getZkConnectString(), jedisConfig.getZkSessionTimeout())
			        .zkProxyDir(jedisConfig.getZkProxyPath())
			        .poolConfig(createJedisPoolConfig())
			        .password(jedisConfig.getSessionAuth())
			        .database(jedisConfig.getDatabase())
			        .build();
		} catch (Exception e) {
			LOGGER.error("Failed to create jedisPool!", e);
		}
        LOGGER.info("Create jedisPool success!");
        return jedisPool;
    }
    
    private JedisPoolConfig createJedisPoolConfig() {
    	JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    	jedisPoolConfig.setMaxTotal(jedisConfig.getMaxTotal());
    	jedisPoolConfig.setMaxIdle(jedisConfig.getMaxIdle());
    	jedisPoolConfig.setMinIdle(jedisConfig.getMinIdle());
    	jedisPoolConfig.setMaxWaitMillis(jedisConfig.getMaxWaitMillis());
    	return jedisPoolConfig;
    }
    
}
